<style scoped>
.markdown {
    width: 100%;
    margin: 0 auto;
}

.title {
    position: relative;
    border-bottom: black 1px solid;
    height: 30px;
    width: 50vw;
    margin: 20px 0 10px 0;
    left: 50%;
    transform: translate(-50%, -50%);

    input {
        width: 50vw;
        border: none;
        text-align: center;
        font-size: 24px;
        font-weight: bold;
    }

    input:focus {
        outline: none;
    }
}

.option_list {
    width: 100%;
    display: flex;
    justify-content: center;
    margin: 10px 0;
}

.supplement_input {
    position: relative;
    width: 50vw;
    left: 50%;
    transform: translate(-50%, 0%);
    background: #ffffff;
    margin-top: 20px;
    padding: 10px;
    border-radius: 10px;
    display: flex;
    flex-direction: column;

    .label {
        width: 75px;
    }

    .row {
        display: flex;
        align-items: center;
        margin: 5px;
    }

    .inputData {
        width: 100%;
    }
}

.upload-box {
    width: 100px;
    height: 100px;
    border: 2px solid #bfbfbf;
    background-color: #f7f7f7;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.upload-box img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    display: none;
}

.upload-box input[type="file"] {
    position: absolute;
    width: 100%;
    height: 100%;
    opacity: 0;
    cursor: pointer;
}
</style>
<template>
    <div style="background: #f5f6f7;min-height: 100vh;">
        <div class="title">
            <input type="text" class="title_input" v-model="title" placeholder="请输入标题">
        </div>
        <mavon-editor class="markdown" ref="myEditor" v-model="markdownContent" :language="language"
            :font-size="fontSize" :scroll-style="scrollStyle" :box-shadow="boxShadow" :box-shadow-style="boxShadowStyle"
            :transition="transition" :toolbars-background="toolbarsBackground" :preview-background="previewBackground"
            :subfield="subfield" :default-open="defaultOpen" :placeholder="placeholder" :editable="editable"
            :code-style="codeStyle" :toolbars-flag="toolbarsFlag" :navigation="navigation" :short-cut="shortCut"
            :autofocus="autofocus" :ishljs="ishljs" :image-filter="imageFilter" :image-click="imageClick"
            :tab-size="tabSize" :html="html" :xss-options="xssOptions" :toolbars="toolbars" @change="handleChange"
            @save="handleSave" @fullScreen="handleFullScreen" @readModel="handleReadModel" @htmlCode="handleHtmlCode"
            @subfieldToggle="handleSubfieldToggle" @previewToggle="handlePreviewToggle" @helpToggle="handleHelpToggle"
            @navigationToggle="handleNavigationToggle" @imgAdd="handleImageAdd" @imgDel="handleImageDelete">
        </mavon-editor>
        <div class="supplement_input">
            <div class="tags row">
                <div class="label">文章标签</div>
                <div class="inputData">
                    <el-select v-model="supplementInput.tags" multiple filterable allow-create default-first-option
                        placeholder="请选择文章标签" style="width: 100%;">
                        <el-option v-for="item in tagsData.options" :key="item.value" :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </div>
            </div>
            <div class="cover row">
                <div class="label">添加封面</div>
                <div class="inputData">
                    <div class="upload-box" id="uploadBox">
                        <img id="preview" src="" alt="Image Preview">
                        <input type="file" accept="image/*" @change="inportCover">
                    </div>
                </div>
            </div>
            <div class="abstract row">
                <div class="label">文章摘要</div>
                <div class="inputData">
                    <el-input type="textarea" :rows="2" placeholder="请输入内容" v-model="supplementInput.summary">
                    </el-input>
                </div>
            </div>
            <div class="category row">
                <div class="label">分类</div>
                <div class="inputData">
                    <el-select v-model="supplementInput.category" filterable placeholder="请选择" style="width: 100%;">
                        <el-option v-for="item in categoryData.options" :key="item.value" :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </div>
            </div>
            <div class="type row">
                <div class="label">文章类型</div>
                <div class="inputData">
                    <el-radio-group v-model="supplementInput.type">
                        <el-radio v-for="option in radioData.options" :key="option.value" :label="option.label">
                            {{ option.label }}
                        </el-radio>
                    </el-radio-group>
                </div>
            </div>
        </div>

        <div class="option_list">
            <div class="option">
                <el-button type="primary" @click="submit">保存</el-button>
            </div>
        </div>
    </div>
</template>

<script>
import Vue from "vue";
import { mavonEditor } from "mavon-editor";
import "mavon-editor/dist/css/index.css";
import request from "@/utils/request";
import MarkdownIt from 'markdown-it';
import axios from "axios";
Vue.component("mavon-editor", mavonEditor);
import { baseURL, imageURL } from "@/utils/request";
import { CategoryEnum,ArticleTypeEnum } from '@/utils/commonEnum';
export default {
    data() {
        return {
            title: '',
            markdownContent: '', // 这里是绑定的Markdown内容
            language: "zh-CN", //语言选择，暂支持 zh-CN: 简体中文, zh-TW: 正体中文 ， en: 英文 ， fr: 法语， pt-BR: 葡萄牙语， ru: 俄语， de: 德语， ja: 日语 |
            fontSize: "14px", //编辑区域文字大小
            scrollStyle: true, // 开启滚动条样式(暂时仅支持chrome)
            boxShadow: true, // 开启边框阴影
            boxShadowStyle: "0 2px 12px 0 rgba(0, 0, 0, 0.1)", // 边框阴影样式
            transition: true, // 是否开启过渡动画
            toolbarsBackground: "#ffffff", // 工具栏背景颜色
            previewBackground: "#fbfbfb", // 预览框背景颜色
            subfield: true, // true： 双栏(编辑预览同屏)， false： 单栏(编辑预览分屏)
            defaultOpen: "preview", // 在单栏（`subfield=false`）时默认展示区域. edit： 默认展示编辑区域， preview： 默认展示预览区域 其他 = edit
            placeholder: "开始编辑...", // 输入框为空时默认提示文本
            editable: true, // 是否允许编辑
            codeStyle: "code-github", // markdown样式： 默认github, [可选配色方案](/mavonEditor/src/lib/core/hljs/lang.hljs.css.js)
            toolbarsFlag: true, // 工具栏是否显示
            navigation: false, // 默认展示目录
            shortCut: true, // 是否启用快捷键
            autofocus: true, // 自动聚焦到文本框
            ishljs: true, // 代码高亮
            imageFilter: null, // 图片过滤函数，参数为一个`File Object`，要求返回一个`Boolean`, `true`表示文件合法，`false`表示文件不合法
            imageClick: null, // 图片点击事件，默认为预览，可覆盖
            tabSize: "\t", // tab转化为几个空格，默认为\t
            html: true, // 启用HTML标签，因为历史原因这个标记一直默认为true，但建议不使用HTML标签就关闭它，它能彻底杜绝安全问题。
            xssOptions: {}, // xss规则配置, 默认开启，设置false可以关闭，开启后会对HTML标签进行过滤，默认过滤所有HTML标签属性，建议按需配置白名单减少被攻击的可能。- 自定义规则参考: [https://jsxss.com/zh/options.html](https://jsxss.com/zh/options.html)- 参考DEMO: [dev-demo](/mavonEditor/src/dev/editor.vue)
            toolbars: {  // 工具栏显示那些工具
                bold: true, // 粗体
                italic: true, // 斜体
                header: true, // 标题
                underline: true, // 下划线
                strikethrough: true, // 中划线
                mark: true, // 标记
                superscript: true, // 上角标
                subscript: true, // 下角标
                quote: true, // 引用
                ol: true, // 有序列表
                ul: true, // 无序列表
                link: true, // 链接
                imagelink: true, // 图片链接
                code: true, // code
                table: true, // 表格
                fullscreen: true, // 全屏编辑
                readmodel: true, // 沉浸式阅读
                htmlcode: true, // 展示html源码
                help: true, // 帮助
                /* 1.3.5 */
                undo: true, // 上一步
                redo: true, // 下一步
                trash: true, // 清空
                save: true, // 保存（触发events中的save事件）
                /* 1.4.2 */
                navigation: true, // 导航目录
                /* 2.1.8 */
                alignleft: true, // 左对齐
                aligncenter: true, // 居中
                alignright: true, // 右对齐
                /* 2.2.1 */
                subfield: true, // 单双栏模式
                preview: true, // 预览
            },
            contentArray: [],
            index: 0,
            eachText: [],
            lastExecutedTime: 0,
            tagsData: {
                options: [],
            },
            categoryData: {
                options: [
                    CategoryEnum.FLOWER,
                    CategoryEnum.BONSAI,
                    CategoryEnum.SUCCULENT,
                    CategoryEnum.FRUIT_TREE
                ],
            },
            radioData: {
                options:null,
            },
            supplementInput: {
                tags: [],
                category: '',
                cover: null,
                summary: '',
                type: '',
            }
        };
    },
    computed: {
        categoryData_options() {
            return Object.values(CategoryEnum);
        },
        articleType_options() {
            return Object.values(ArticleTypeEnum);
        },
        
    },
    created() {
        this.categoryData.options = this.categoryData_options;
        this.radioData.options = this.articleType_options;
    },
    mounted() {
        // 假设这个方法是用来获取Markdown内容的
        this.fetchMarkdownData();
    },
    methods: {
        fetchMarkdownData() {
            this.markdownContent = '# Hello Markdown\n这里是Markdown的示例内容\n';

        },
        handleChange(value, render) {
            // 定义正则表达式
            var regex = /!\[([^\[\]]+)\]\(([^)]+)\)/g;
            this.contentArray[this.index] = value.match(regex);
            var curImage = this.contentArray[this.index]
            var preImage = this.contentArray[(this.index + 1) % 2]
            this.index = (this.index + 1) % 2
            console.log(curImage);
            console.log(preImage);
            //新增的图片
            console.log(this.difference(curImage, preImage));
            //删除的图片
            console.log(this.difference(preImage, curImage));
        },
        difference(arr1, arr2) {
            return arr1.filter(value => !arr2.includes(value));
        },
        handleSave(value, render) {
            console.log("保存内容:", value);
            console.log("Markdown 解析结果:", render);
            if (this.title == null || this.title == '') {
                this.$message({
                    message: '请输入标题',
                    type: 'error'
                });
                return;
            }
            if (this.supplementInput.tags.length == 0 || this.supplementInput.category == null || this.supplementInput.summary == null || this.supplementInput.type == null) {
                this.$message({
                    message: '标签，分类，摘要，类型均要填写哦！',
                    type: 'error'
                });
                return;
            }
            const now = Date.now();
            if (now - this.lastExecutedTime >= 3000) {
                const md = new MarkdownIt();
                const tokens = md.parse(value, {});

                tokens.forEach(token => {
                    if (token.type === 'inline' && token.children) {
                        token.children.forEach(child => {
                            if (child.type === 'text') {
                                const sentences = child.content.split(/(?<=。)/); // 分割时保留句号
                                sentences.forEach(sentence => {
                                    if (sentence.trim()) {
                                        this.eachText.push(sentence.trim());
                                    }
                                });
                            }
                        });
                    }
                });
                for (var i = 0; i < this.eachText.length; i++) {
                    //如果value中包含eachText中的内容，则将value的值替换为<span class="em">eachText[i]</span>
                    if (render.includes(this.eachText[i])) {
                        render = render.replace(this.eachText[i], `<span class="em" id="text${i}">${this.eachText[i]}</span>`);
                    }
                }
                //将标签转化成以;分割的字符串
                var tagsStr = this.supplementInput.tags.join(';');
                console.log(tagsStr);
                console.log(this.supplementInput);
                var token = localStorage.getItem('token');
                request.post("http://localhost:9090/posts", {
                    content: render,
                    categoryId: this.supplementInput.category,
                    tokens: token,
                    tags: tagsStr,
                    status: 2,
                    articleType: this.supplementInput.type,
                    cover: this.supplementInput.cover,
                    title: this.title,
                    views: 0,
                    likes: 0,
                    commentsCount: 0,
                    collectCount: 0
                }).then(res => {
                    this.$message({
                        message: '发布成功',
                        type: 'success'
                    });
                    //1秒后跳转到首页
                    setTimeout(() => {
                        this.$router.push('/');
                    }, 1000);
                });
                this.lastExecutedTime = now;
            } else {
                this.$message({
                    message: '3秒内只能点一次',
                    type: 'error'
                });
            }
        },
        handleFullScreen(status, value) {
            console.log("全屏编辑状态:", status);
            console.log("Markdown 解析结果:", value);
        },
        handleReadModel(status, value) {
            console.log("沉浸式阅读状态:", status);
            console.log("Markdown 解析结果:", value);
        },
        handleHtmlCode(status, value) {
            console.log("查看 HTML 源码状态:", status);
            console.log("Markdown 解析结果:", value);
        },
        handleSubfieldToggle(status, value) {
            console.log("单双栏编辑状态:", status);
            console.log("Markdown 解析结果:", value);
        },
        handlePreviewToggle(status, value) {
            console.log("预览编辑状态:", status);
            console.log("Markdown 解析结果:", value);
        },
        handleHelpToggle(status, value) {
            console.log("帮助开启状态:", status);
            console.log("Markdown 解析结果:", value);
        },
        handleNavigationToggle(status, value) {
            console.log("导航目录开启状态:", status);
            console.log("Markdown 解析结果:", value);
        },
        async handleImageAdd(pos, file) {
            console.log(pos);
            let entireUrl = null;
            try {
                // 创建FormData对象并添加文件
                let formData = new FormData();
                formData.append('image', file);

                // 发送图片到服务器
                axios.post(baseURL + 'upload/image', formData, {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                }).then(response => {
                    entireUrl = imageURL + response.data;
                    console.log("entireUrl:", entireUrl);
                    this.$refs.myEditor.$img2Url(pos, entireUrl);
                }).catch(err => {
                    console.error('上传失败:', err);
                });
            } catch (error) {
                console.error('图片上传失败', error);
            }
        },

        handleImageDelete(pos, imgFile) {
            console.log("删除图片，位置:", pos);
            console.log("图片文件:", imgFile);
            var url = pos[0]
            url = url.replace(imageURL, "")
            request.delete(`upload/image/${url}`).then(res => {
                console.log(res);
            })
        },
        async uploadImage() {
            const formData = new FormData();
            formData.append('image', this.selectedFile);

        },
        inportCover(event) {
            const file = event.target.files[0];
            const reader = new FileReader();
            const self = this;

            reader.onload = function (e) {
                let entireUrl = null;
                try {
                    // 创建FormData对象并添加文件
                    let formData = new FormData();
                    formData.append('image', file);

                    // 发送图片到服务器
                    axios.post(baseURL + 'upload/image', formData, {
                        headers: {
                            'Content-Type': 'multipart/form-data'
                        }
                    }).then(response => {
                        entireUrl = imageURL + response.data;
                        self.supplementInput.cover = entireUrl;
                    }).catch(err => {
                        console.error('上传失败:', err);
                    });
                } catch (error) {
                    console.error('图片上传失败', error);
                }
                const imgElement = document.getElementById('preview');
                imgElement.src = e.target.result;
                imgElement.style.display = 'block';
            };

            if (file) {
                reader.readAsDataURL(file);
            }
        },
        submit() {
            const md = new MarkdownIt();
            var analysisContent = md.render(this.markdownContent);
            if (this.title == null || this.title == '') {
                this.$message({
                    message: '请输入标题',
                    type: 'error'
                });
                return;
            }
            if (this.supplementInput.tags.length == 0 || this.supplementInput.category == null || this.supplementInput.summary == null || this.supplementInput.type == null) {
                this.$message({
                    message: '标签，分类，摘要，类型均要填写哦！',
                    type: 'error'
                });
                return;
            }
            const now = Date.now();
            if (now - this.lastExecutedTime >= 3000) {
                const md = new MarkdownIt();
                const tokens = md.parse(this.markdownContent, {});

                tokens.forEach(token => {
                    if (token.type === 'inline' && token.children) {
                        token.children.forEach(child => {
                            if (child.type === 'text') {
                                const sentences = child.content.split(/(?<=。)/); // 分割时保留句号
                                sentences.forEach(sentence => {
                                    if (sentence.trim()) {
                                        this.eachText.push(sentence.trim());
                                    }
                                });
                            }
                        });
                    }
                });
                for (var i = 0; i < this.eachText.length; i++) {
                    if (analysisContent.includes(this.eachText[i])) {
                        analysisContent = analysisContent.replace(this.eachText[i], `<span class="em" id="text${i}">${this.eachText[i]}</span>`);
                    }
                }
                //将标签转化成以;分割的字符串
                var tagsStr = this.supplementInput.tags.join(';');
                console.log(analysisContent);
                var token = localStorage.getItem('token');
                request.post("http://localhost:9090/posts", {
                    content: analysisContent,
                    categoryId: this.supplementInput.category,
                    tokens: token,
                    tags: tagsStr,
                    status: 2,
                    // articleType: this.supplementInput.type,
                    articleType: 1,
                    cover: this.supplementInput.cover,
                    summary: this.supplementInput.summary,
                    title: this.title,
                    views: 0,
                    likes: 0,
                    commentsCount: 0,
                    collectCount: 0,
                }).then(res => {
                    this.$message({
                        message: '发布成功',
                        type: 'success'
                    });
                    //1秒后跳转到首页
                    setTimeout(() => {
                        this.$router.push('/');
                    }, 1000);
                });
                this.lastExecutedTime = now;
            } else {
                this.$message({
                    message: '3秒内只能点一次',
                    type: 'error'
                });
            }
        }
    },
}
</script>